//
//  NetworkTools.swift
//  微博Swift
//
//  Created by  justinchou on 16/2/24.
//  Copyright © 2016年  justinchou. All rights reserved.
//

import UIKit
import AFNetworking

typealias JustinRequestCallBack = ()->()

enum JustinRequestMethod: String {
    case POST = "POST"
    case GET = "GET"
}

class NetworkTools: AFHTTPSessionManager {
    
    let appkey = "533743590"
    let appSecret = "aa6812034464029102fa5c4bd085d36d"
    let redirectUri = "http://www.baidu.com"

    // MARK: - 是否连接的计算型属性--为了判断后续的cell为0还是为1
    var reachable: Bool {
        return reachabilityManager.reachable
    }
    
    static let sharedTools: NetworkTools = {
        let instance = NetworkTools()

        //设置超时延迟
        instance.requestSerializer.timeoutInterval = 10
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        //空值过滤，如果kvc得到空值会导致崩溃
        (instance.responseSerializer as! AFJSONResponseSerializer).removesKeysWithNullValues = true
        
        //设置连接监控
        instance.reachabilityManager.setReachabilityStatusChangeBlock() { (status) -> Void in
            //发送通知
            NSNotificationCenter.defaultCenter().postNotificationName(JustinWeiBoNetworkReachabilityNotification, object: nil)
        }
        //开始进行监控
        instance.reachabilityManager.startMonitoring()
        
        return instance
    }()
    
    deinit {
        reachabilityManager.stopMonitoring()
    }
    
    func request(
        method: JustinRequestMethod,
        urlString: String,
        parameters: [String: AnyObject]?,
        finished: (result:[String : AnyObject]?) -> ()){
            
            /// 成功回调
            let success = { (task : NSURLSessionDataTask, responseObject : AnyObject?) -> Void in
                if let result = responseObject as? [String : AnyObject] {
                    finished(result: result)
                } else {
                    print("数据错误")
                    finished(result: nil)
                }
            }
            /// 失败回调
            let failure = { (task : NSURLSessionDataTask?, error : NSError) -> Void in
                print("网络请求错误\(error)")
                finished(result: nil)
            }
            
            if method == .GET {
                GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
            } else {
                POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
            }
    }
    
    /// 加载请求码
    ///
    /// - parameter code:     请求码
    /// - parameter finished: 完成回调
    func loadAccessToken(code: String, finished: ([String: AnyObject]?)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": appkey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]
        
        request(.POST, urlString: urlString, parameters: params) { [weak self] result in
            
            guard let uid = result!["uid"] as? String,
                access_token = result!["access_token"] as? String else {
                    
                    print("Token数据错误")
                    
                    finished(nil)
                    
                    return
            }
            
            self?.loadUserInfo(uid, access_token: access_token, finished: { userDict in
                
                guard var userDict = userDict else {
                    print("用户数据错误")
                    finished(nil)
                    return
                }
                
                for (k, v) in result! {
                    userDict[k] = v
                }
                
                finished(userDict)
                
            })
            
        }
        
    }    
    
}










